package cn.moefly.common.helper;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;

/**
 * SnowFlake 雪花算法优化方案
 * 1. 因为原来的雪花算法在访问低的时候会经常有可能造成序列浪费，当访问量高（每毫秒超过4096个，但其实基本不可能达到这个速度）又会暂停等待下一时间戳，所以把时间戳减少10位，并把时间更新幅度变为秒级
 * 2. 32bit时间位可以用大概136年
 *
 * 1bit(符号位) 7bit(location id) + 7bit(machine id) + 32bit(timestamp) + 18bit(序列号)
 */

@Slf4j
public class SnowFlakeAdvanceIdGenerator {

    //初始时间戳
    final static long START_TIMESTAMP = 1588093469564L;

    //数据长度
    final static int LOCATION_ID_BITS = 7;
    final static int MACHINE_ID_BITS = 7;
    final static int TIMESTAMP_BITS = 32;
    final static int SEQUENCE_BITS = 18;

    final long prefix;
    //最大值
    final static long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);
    final static long MAX_DATA_CENTER_ID = ~(-1L << LOCATION_ID_BITS);
    final static long MAX_DATA_CENTER_ID_2 = (long) Math.pow(2, LOCATION_ID_BITS) - 1;
    final static long MAX_WORKER_ID = ~(-1L << MACHINE_ID_BITS);
    final static long MAX_WORKER_ID_2 = (long) Math.pow(2, MACHINE_ID_BITS) - 1;
    final static long MAX_SEQUENCE_2 = (long) Math.pow(2, SEQUENCE_BITS) - 1;

    // 1bit +４1bit(timestamp) + 5bit(data center id) + 5bit(worker id) + 12bit(序列号)
    //工作id需要左移的位数，12位
    final static int WORKER_ID_SHIFT = SEQUENCE_BITS;
    //数据id需要左移位数 12+5=17位
    final static int DATA_CENTER_ID_SHIFT = MACHINE_ID_BITS + SEQUENCE_BITS;
    //时间戳需要左移位数 12+5+5=22位
    final static int TIMESTAMP_SHIFT = LOCATION_ID_BITS + MACHINE_ID_BITS + SEQUENCE_BITS;

    //下面两个每个5位，加起来就是10位的工作机器id
    private long workerId;    //机器id
    private long dataCenterId;   //机房id
    //12位的序列号
    private AtomicLong sequence = new AtomicLong(0L);

    //上次时间戳，初始值为负数
    private long lastTimestamp = -1L;

    public SnowFlakeAdvanceIdGenerator(long locationId, long machineId) {
        // sanity check for workerId
        assert LOCATION_ID_BITS + MACHINE_ID_BITS + TIMESTAMP_BITS + SEQUENCE_BITS + 1 == 64;
        this.prefix = (locationId << MACHINE_ID_BITS) | (machineId << TIMESTAMP_BITS + SEQUENCE_BITS);
    }


    //下一个ID生成算法
    public synchronized long nextId() {
        long currentTime = currentTime();

        //获取当前时间戳如果小于上次时间戳，则表示时间戳获取出现异常
        if (currentTime < lastTimestamp) {
            log.error("clock is moving backwards.  Rejecting requests until {}.", lastTimestamp);
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds",
                    lastTimestamp - currentTime));
        }

        //获取当前时间戳如果等于上次时间戳（同一毫秒内），则在序列号加一；否则序列号赋值为0，从0开始。
        if (lastTimestamp == currentTime) {
            var seq = sequence.updateAndGet(operand -> {
                if (operand == MAX_SEQUENCE){
                    tilNextMillis(lastTimestamp);
                    return 0;
                } else {
                    return operand + 1;
                }
            });
        } else {
            sequence.set(0);
            //将上次时间戳值刷新
            lastTimestamp = currentTime;
        }


        /**
         * 返回结果：
         * 1bit(正数永远为0) +４1bit(timestamp) + 5bit(data center id) + 5bit(worker id) + 12bit(序列号)
         * | 是按位或运算符，例如：x | y，只有当x，y都为0的时候结果才为0，其它情况结果都为1。
         * 因为个部分只有相应位上的值有意义，其它位上都是0，所以将各部分的值进行 | 运算就能得到最终拼接好的id
         */
//        return ((currentTime - START_TIMESTAMP) << TIMESTAMP_SHIFT) |
//                (dataCenterId << DATA_CENTER_ID_SHIFT) |
//                (workerId << WORKER_ID_SHIFT) |
//                sequence;

        //TODO： 这个优化雪花的东西我居然忘记了继续做了，先马克一下
        return 0;
    }

    //获取时间戳，并与上次时间戳比较
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = currentTime();
        while (timestamp <= lastTimestamp) {
            timestamp = currentTime();
        }
        return timestamp;
    }

    //获取系统时间戳
    private long currentTime() {
        return System.currentTimeMillis();
    }


}
